package com.ecas.code.generator.controller.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class CodeGeneratorAspectj {
    private static final Logger log = LoggerFactory.getLogger(CodeGeneratorAspectj.class);

   @Before("execution(  public  * com.ecas.code.generator.controller.*.*(..))")
   public void log() {
       log.info("before aspect log:");
   }

    @Pointcut("execution( public * com.ecas.code.generator.controller.*.*(..))")
    private void  aspectMethod() {
        log.info("aspectMethod method executing...");
    }

    @Around("aspectMethod()")
    public Object adviceAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        log.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

        // result的值就是被拦截方法的返回值
        Object result = proceedingJoinPoint.proceed();

        log.info("请求结束，controller的返回值是 " +request.getContextPath() );
        return result;
    }
}
